from django.db import models
from django.contrib.auth.models import User

class ZoneManager(models.Manager):
	def for_hostname(self, hostname):
		candidate_zones = [ hostname ]
		zone = hostname
		while zone != '':
			beginning, sep, zone = zone.partition('.')
			candidate_zones += [zone]
		for zone in candidate_zones:
			try:
				return self.get(domain=zone)
			except Zone.DoesNotExist:
				pass
		raise Zone.DoesNotExist('No zone contains name %s' % hostname)
				

class Zone(models.Model):
	"""
	A Zone is a DNS domain that may contain dynamic hosts.
	"""
	domain = models.CharField(max_length=127, unique=True)
	owner = models.ForeignKey(User)
	
	objects = ZoneManager()
	
	def store(self):
		from lddns_web.dddatafile import Store
		from os.path import join
		from django.conf import settings
		return Store(join(settings.ZONE_DIR, self.domain), zone=self.domain)

	def __unicode__(self):
		return '%s (%s)' % (self.domain, self.owner)
	
		
	class Admin:
		pass
